import apiTransformApi from '../../yali-sdk/business/live/api/apiTransformApi';
import { SUCCESS } from '../../yali-sdk/utils/success';
import { FAIL } from '../../yali-sdk/utils/fail';
//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    list: [],
    duration: 2000,
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    loading: false,
    plain: false
  },
  //事件处理函数
  bindViewTap: function(e) {
    wx.navigateTo({
      url: '../detail/detail?id=' + e.target.dataset.id
    })
  },
  loadMore: function (e) {
    if (this.data.list.length === 0) return
    var date = this.getNextDate()
    var that = this
    var time =Number(formatDate(date));
    that.setData({ loading: true })
    global.actionDispatcher.execute(apiTransformApi,{time,before:'before'}, (f,fs) => {
        if (f === SUCCESS) {
            that.setData({
            loading: false,
            list: that.data.list.concat([{ header: formatDate(date, '-') }]).concat(fs.data.stories)
         })
        }
    });
  },
  getNextDate: function (){
    var now = new Date()
    now.setDate(now.getDate() - this.index++)
    return now
  },
  onLoad: function () {
    var that = this
     global.actionDispatcher.execute(apiTransformApi, {latest:'latest'}, (f,fs) => {
        if (f === SUCCESS) {
             that.setData({
              banner:fs.data.top_stories,
              list: [{ header: '相关推荐' }].concat(fs.data.stories)
          })
        }
    });
    this.index = 1
    //调用应用实例的方法获取全局数据
    // app.getUserInfo(function(userInfo){
    //   //更新数据
    //   that.setData({
    //     userInfo:userInfo
    //   })
    // })
    
  }
})
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatDate(date, split) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join(split || '')
}


function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime,
  formatDate: formatDate
}
